package com.example.imoocmusicdemo.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import com.example.imoocmusicdemo.helps.MediaPlayerHelp;
import com.example.imoocmusicdemo.models.MusicModel;

/**
 * 1.通过 Service 连接 PlayMusicView 和 MediaPlayHelper
 * 2.PlayMusicView —— Service
 *      （1）播放音乐、暂停音乐
 *      （2）启动、绑定Service，解除绑定Service
 * 3.MediaPlayerHelper —— Service
 *      （1）播放音乐、暂停音乐
 *      （2）监听音乐播放完成，停止Service
 * */

public class MusicService extends Service {

    private MediaPlayerHelp mMediaPlayerHelp;
    private MusicModel mMusicModel;

    public MusicService() {
    }

    public class MusicBind extends Binder{
        /**
         * 设置音乐（MusicModel）
         * */
        public void setMusic(MusicModel musicModel){
            mMusicModel = musicModel;
        }

        /**
         * 播放音乐
         * */
        public void playMusic(){
            /**
             * 1.判断当前音乐是否已经在播放
             * 2.在播放则执行start方法
             * 3.如果不是需要播放的音乐，则调用setPath方法
             * */
            if (mMediaPlayerHelp.getPath()!= null && mMediaPlayerHelp.getPath().equals(mMusicModel.getPath())){
                mMediaPlayerHelp.start();
            }else {
                mMediaPlayerHelp.setPath(mMusicModel.getPath());
                mMediaPlayerHelp.setOnMediaPlayerHelperListener(new MediaPlayerHelp.OnMediaPlayerHelperListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mMediaPlayerHelp.start();
                    }

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        stopSelf();
                    }
                });
            }
        }


        /**
         * 暂停播放
         * */
        public void stopMusic(){
            mMediaPlayerHelp.pause();
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBind();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mMediaPlayerHelp = MediaPlayerHelp.getInstance(this);

    }
}
